package MTT::Controller::Reports;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Reports - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut
use Data::Dumper;

use utf8;

use MTT::Libs::ObjectAccess;
use MTT::Form::Template;




sub index :Path {
    my ( $self, $c, $id_type, $id_switch ) = @_;

	warn "----- 13 ----- $id_type, $id_switch >>>";

	my $oa = MTT::Libs::ObjectAccess->instance();
	my $switches = {};
	if ( !$id_type && !$id_switch ) {
		my @types = $c->model('DBIC::SwitchType')->all();

		foreach my $type ( @types ) {
			next unless $oa->check_objects_access($c, 'Оборудование', $type->id) || $c->check_user_roles('admin');
			push @{ $switches->{type} }, $type;
		}
	}
	elsif ( !$id_switch ) {
		if ( $oa->check_objects_access($c, 'Оборудование', $id_type) || $c->check_user_roles('admin') ) {
			my $type = $c->model('DBIC::SwitchType')->find($id_type);
			if ($type) {
				push @{ $switches->{type} }, $type;
				my $sws = $c->model('DBIC::Switch')->search({id_type => $type->id});
				while ( my $switch = $sws->next() ) {
					push @{ $switches->{switch_do} }, $switch;
				}
			}
		}
	}
	else {
		if ( $oa->check_objects_access($c, 'Оборудование', $id_type) || $c->check_user_roles('admin') ) {
			my $switch = $c->model('DBIC::Switch')->find({id => $id_switch});
			push @{ $switches->{switch_do} }, $switch if $switch;
		}
	}

	$c->stash(switches => $switches);

	my $form = MTT::Form::Template->new(
		schema => $c->model('DBIC')->schema,
		ctx => $c	
	);
warn "-------- 42 -------->>>" . Dumper( $form->field('switch_type')->options );
	$c->stash(
		template => 'template.tt2',
		form => $form
	);

}

sub get_switches: Path('/reports/switches') {
	my ($self, $c) = @_;

	my $type_ids = $c->req->params->{'switch_types[]'};
	$type_ids = [ $type_ids ] unless ref $type_ids;

	my @switches;
	foreach my $id_type ( @$type_ids ) {
		my $switches = $c->model('DBIC::Switch')->search({id_type => $id_type});
		while ( my $switch = $switches->next() ) {
			push @switches, {id => $switch->id, name => $switch->descr};
		}
	}

#	$c->component('View::JSON')->encoding('utf8');
	$c->stash->{json_data} = { switches => \@switches };
	$c->forward('View::JSON');
}


=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
